package com.wnxy.portal.controller;

import cn.hutool.core.util.RandomUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 注入rabbit模板工具类
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/{email}")
    public String sendEmail(@PathVariable("email") String email) {
        // 设置邮件内容: 四位随机数
        String code = RandomUtil.randomNumbers(4);
        // map封装消息内容
        Map<String,String> emailMap = new HashMap<>();
        emailMap.put("from",from);
        emailMap.put("to",email);
        emailMap.put("subject","验证码邮件");
        emailMap.put("code",code);

        // 发送消息到rabbitmq队列中
        // 参数1：指定routingKey路由key，但是如果是简单模式，这里是队列名称
        // 参数2：消息内容
        rabbitTemplate.convertAndSend("q-mail",emailMap);

        // 验证码存储到redis，有效时间5分钟
        stringRedisTemplate.opsForValue().set(email,code, Duration.ofMinutes(5));

        return "ok";
    }
}
